const db = require('../config/db');
const { success, fail } = require('../utils/response');

exports.getAddresses = async (req, res) => {
  const [rows] = await db.query('SELECT * FROM Address WHERE user_id=?', [req.user.id]);
  res.json(success(rows));
};

exports.getAddressById = async (req, res) => {
  const { id } = req.params;
  const [rows] = await db.query('SELECT * FROM Address WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!rows.length) return res.json(fail('地址不存在'));
  res.json(success(rows[0]));
};

exports.createAddress = async (req, res) => {
  const { name,gender, phone, province, city, district,detail } = req.body;
  await db.query('INSERT INTO Address (user_id, name,gender, phone, province, city, district,detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [req.user.id,name,gender, phone, province, city, district,detail]);
  res.json(success());
};

exports.updateAddress = async (req, res) => {
  const { id } = req.params;
  const { name,gender, phone, province, city, district,detail } = req.body;
  
  // 检查地址是否存在
  const [rows] = await db.query('SELECT id FROM Address WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!rows.length) return res.json(fail('地址不存在'));
  
  await db.query('UPDATE Address SET name=?,gender=?, phone=?, province=?, city=?, district=?,detail=? WHERE id=?', [name,gender, phone, province, city, district,detail, id]);
  res.json(success());
};

exports.deleteAddress = async (req, res) => {
  const { id } = req.params;
  
  // 检查地址是否存在
  const [rows] = await db.query('SELECT id FROM Address WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!rows.length) return res.json(fail('地址不存在'));
  
  await db.query('DELETE FROM Address WHERE id=?', [id]);
  res.json(success());
};    